package backstage.sys.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import backstage.staff.pojo.Staff;

public class LoginFilter implements Filter {

	public void init(FilterConfig arg0) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpreq = (HttpServletRequest) request;
        HttpServletResponse httpres = (HttpServletResponse) response;
        String url = httpreq.getRequestURI();
        String path = request.getServerName()+":"+request.getServerPort()+httpreq.getContextPath();
        if( -1 != url.indexOf(".jsp") && -1 == url.indexOf("login.jsp")){
        	HttpSession session = httpreq.getSession();
        	Staff staff = (Staff)session.getAttribute("staff");
        	if(null == staff){
        		httpres.sendRedirect("http://" + path + "/backstage/login.jsp");
        	}else if(null == staff.getId()){
        		httpres.sendRedirect("http://" + path + "/backstage/login.jsp");
        	}else{
        		chain.doFilter(request, response);
        	}
        }else{
        	chain.doFilter(request, response);
        }
	}

	public void destroy() {
		
	}
}
